
from fastapi import FastAPI
from sqlalchemy import select
from initialization.dbInit import engine, get_async_session
from initialization.redisInit import sync_pool, redis_pool, get_async_redis
from model.entitys import get_sync_db, ScheduledTask, Status, to_json, create_table_all, CaseGroup, sync_engine
from service.webService import add_task
from variable import dependent_data, case_thread_pool, file_thread_pool, application_thread_pool, write_thread_pool, \
    command_thread_pool, handle_thread_pool

def load_scheduled_tasks():
    session = get_sync_db()

    scheduled_task_list = to_json(session.query(ScheduledTask).filter(ScheduledTask.enable == Status.VALID).all())
    for st in scheduled_task_list:
        add_task(st)

    session.close()

async def empty_group_cache():
    session = await get_async_session()
    redis = await get_async_redis()

    case_group_id_list = (await session.execute(select(CaseGroup.id))).scalars().all()
    if case_group_id_list:
        await redis.delete(*case_group_id_list)

    await session.close()
    await redis.close()

def register_scheduler(app: FastAPI):
    @app.on_event("startup")
    def start_event():
    # async def start_event():
        # dependent_data["sched"].start()
        create_table_all()

        dependent_data["ground_sched"].start()
        load_scheduled_tasks()

    @app.on_event("startup")
    async def start_event():
        # app.state.db = await get_async_session()
        # app.state.redis = await get_async_redis()

        await empty_group_cache()

    @app.on_event("shutdown")
    def shutdown_event():
        case_thread_pool.shutdown()
        file_thread_pool.shutdown()
        handle_thread_pool.shutdown()
        application_thread_pool.shutdown()
        write_thread_pool.shutdown()
        command_thread_pool.shutdown()

        sync_engine.dispose()
        sync_pool.disconnect()

        dependent_data["ground_sched"].shutdown()

    @app.on_event("shutdown")
    async def shutdown_event():
        await engine.dispose()
        await redis_pool.disconnect()

        await empty_group_cache()















































